import re
import time
from datetime import datetime, timedelta
from utils.logger import setup_logger
from utils.config_loader import get_config

logger = setup_logger("danmaku.processor")

class DanmuProcessor:
    def __init__(self):
        self.config = get_config()
        self.user_last_time = {}
        self.blocked_keywords = []
        self.punish_keywords = self._load_keywords_file('config/punish_words.txt')
        self.last_response_time = datetime.now()
        self.punish_count_file = 'config/blacklist_uid.txt'
        self._punish_file_warned = False  # 只提示一次
        self.user_punish_count = self._load_punish_count()  # 记录用户违规次数和拉黑
        self.whitelist = self._load_whitelist('config/whitelist_uid.txt')
        logger.info("弹幕处理器初始化完成")

    def _load_whitelist(self, path) -> dict:
        """加载白名单，返回 {uid: name} 字典"""
        result = {}
        try:
            with open(path, 'r', encoding='utf-8') as f:
                for line in f:
                    line = line.strip()
                    if not line or line.startswith('#'):
                        continue
                    parts = line.split(',')
                    if len(parts) == 2:
                        name, uid = parts[0].strip(), parts[1].strip()
                        try:
                            result[int(uid)] = name
                        except Exception:
                            continue
        except FileNotFoundError:
            logger.info(f"白名单文件不存在: {path}")
        return result

    def _load_punish_count(self) -> dict:
        """从文件加载用户违规次数和拉黑状态"""
        result = {}
        try:
            with open(self.punish_count_file, 'r', encoding='utf-8') as f:
                for line in f:
                    line = line.strip()
                    if not line or line.startswith('#'):
                        continue
                    parts = line.split(',')
                    if len(parts) == 2:
                        try:
                            uid = int(parts[0])
                            count = parts[1]
                            if count == 'ban':
                                result[uid] = 'ban'
                            else:
                                result[uid] = int(count)
                        except Exception:
                            continue
        except FileNotFoundError:
            if not getattr(self, '_punish_file_warned', False):
                logger.warning(f"违规次数/拉黑文件不存在: {self.punish_count_file}")
                self._punish_file_warned = True
        return result

    def _save_punish_count(self):
        """将当前违规次数和拉黑状态写入文件"""
        try:
            with open(self.punish_count_file, 'w', encoding='utf-8') as f:
                f.write('# uid,count\n# （count为数字表示违规次数，为ban表示已拉黑）\n')
                for uid, count in self.user_punish_count.items():
                    if count == 'ban':
                        f.write(f'{uid},ban\n')
                    else:
                        f.write(f'{uid},{count}\n')
        except Exception as e:
            logger.warning(f"写入违规次数/拉黑文件失败: {e}")

    def check_punish(self, user_id: int, text: str) -> int:
        """
        检查弹幕内容是否命中惩罚关键词，白名单用户不受惩罚
        返回 0/1/2/3，分别代表无违规/第一次/第二次/第三次
        命中后自动更新并持久化违规次数，3次及以上自动标记为ban
        """
        if user_id in self.whitelist:
            logger.debug(f"用户 {user_id} 在白名单中，跳过违禁词惩罚")
            return 0
        if any(word in text for word in self.punish_keywords):
            old = self.user_punish_count.get(user_id, 0)
            if old == 'ban':
                return 3
            count = old + 1 if isinstance(old, int) else 1
            if count >= 3:
                self.user_punish_count[user_id] = 'ban'
                self._save_punish_count()
                return 3
            else:
                self.user_punish_count[user_id] = count
                self._save_punish_count()
                return count
        return 0
    """弹幕处理器，负责过滤和管理弹幕"""
    
    # ...见上方重构...

    def _load_keywords_file(self, path) -> list[str]:
        try:
            with open(path, "r", encoding="utf-8") as f:
                return [line.strip() for line in f if line.strip() and not line.startswith('#')]
        except FileNotFoundError:
            logger.warning(f"关键词文件不存在: {path}")
            return []
    
    # _load_blocked_keywords 已废弃
    
    def filter_danmaku(self, user_id: int, text: str) -> tuple[bool, str|None]:
        """多层弹幕过滤，返回(是否通过, 命中违禁词)"""
        # 1. 长度过滤
        if len(text) > 50 or len(text) < 2:
            logger.debug(f"弹幕长度异常，已过滤: {text}")
            return False, None
        # 2. 关键词过滤
        for kw in self.blocked_keywords:
            if kw in text:
                logger.debug(f"弹幕包含屏蔽词[{kw}]，已过滤: {text}")
                return False, kw
        # 3. 符号/表情过滤
        if re.match(r'^[\s\W_\U0001F600-\U0001F64F]+$', text):
            logger.debug(f"弹幕包含过多符号，已过滤: {text}")
            return False, None
        # 4. 用户冷却
        now = datetime.now()
        if user_id in self.user_last_time:
            elapsed = (now - self.user_last_time[user_id]).total_seconds()
            if elapsed < float(self.config["system"]["user_cooldown"]):
                logger.debug(f"用户冷却中，已过滤: {text}")
                return False, None
        # 5. 系统冷却
        elapsed = (now - self.last_response_time).total_seconds()
        if elapsed < float(self.config["system"]["system_cooldown"]):
            logger.debug(f"系统冷却中，已过滤: {text}")
            return False, None
        # 更新最后响应时间
        self.user_last_time[user_id] = now
        self.last_response_time = now
        return True, None